package com.ocom.payconfig.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ocom.common.constant.PayConfigUrl;
import com.ocom.common.entity.card.*;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.payconfig.AddCardInfoVo;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.DateUtil;
import com.ocom.common.utils.DateUtils;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.payconfig.UpdatecardStateVo;
import com.ocom.payconfig.service.*;
import com.ocom.payconfig.vo.GetCardRecordListVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
public class CardInfoController {

    @Autowired
    private XfCardInfoService xfCardInfoService;

    @Autowired
    private CardRecordService cardRecordService;

    @Autowired
    private XfWhiteInfoService xfWhiteInfoService;

    @Autowired
    private XfDeviceInfoService xfDeviceInfoService;


    @Autowired
    private XfAccountInfoService xfAccountInfoService;

    @Autowired
    private PersonnelInfoService personnelInfoService;


    @Autowired
    private XfAccountTypeService xfAccountTypeService;

    // 查询卡信息（getCardInfo）
    @GetMapping(PayConfigUrl.Url_GetCardInfo)
    public Result GetCardInfo(Long comId, String accountNo) {
        if (comId == null) {
            log.info("获取账号类型信息comId为空");
            return ResultUtil.error(ResultEnum.Err_203, "获取账号类型信息comId为空");
        }
        if (accountNo == null || accountNo.isEmpty()) {
            log.info("获取账号类型信息 accountNo 为空");
            return ResultUtil.error(ResultEnum.Err_203, "获取账号类型信息 accountNo 为空");
        }
        return ResultUtil.success(xfCardInfoService.GetCardInfo(comId, accountNo));
    }

    // 查询卡信息（getCardInfo）
    @GetMapping(PayConfigUrl.Url_GetCardInfoByPid)
    public Result GetCardInfoByPid(Long comId, Long pId) {
        EntityCardInfo entityCardInfo = xfCardInfoService.GetCardInfoByPid(comId, pId);
        if (entityCardInfo == null) {
            return ResultUtil.success(entityCardInfo);
        }
        entityCardInfo.setCostFee(0l);
        entityCardInfo.setDeposit(0l);
        EntityCardRecord record = cardRecordService.getRecodeInfo(comId, pId, entityCardInfo.getCardNo());
        if (record != null) {
            entityCardInfo.setCostFee(record.getCostFee());
            entityCardInfo.setDeposit(record.getDeposit());
        }
        return ResultUtil.success(entityCardInfo);
    }

    /**
     * 个人发卡（addCardInfo）
     */
    @PostMapping(PayConfigUrl.Url_AddCardInfo)
    public Result AddCardInfo(@RequestBody AddCardInfoVo addCardInfoVo) {
        log.info("个人发卡請求參數{{}}", addCardInfoVo);

        EntityXfAccountInfo entityXfAccountInfo = null;
        try {
            EntityCardInfo entityCardInfo1 = xfCardInfoService.selectCount(addCardInfoVo.getComId(), addCardInfoVo.getCardNo());
            if (entityCardInfo1 != null) {
                if (entityCardInfo1.getPId().equals(addCardInfoVo.getPId())) {
                    Date date = DateUtil.getDate2(addCardInfoVo.getEndDate(), "yyyy-MM-dd HH:mm:ss");
                    if (date != null && entityCardInfo1.getEndDate().getTime() != date.getTime()) {
                        //更新卡信息；
                        entityCardInfo1.setEndDate(DateUtils.parseDate(addCardInfoVo.getEndDate()));
                        xfCardInfoService.updateCardInfo(addCardInfoVo.getComId(), addCardInfoVo.getPId(), entityCardInfo1);
                        try {
                            //将单位下的所有机器的白名单状态更新为1，
                            // Update xf_device_info set list_state=1 where com_id=@comId
                            xfDeviceInfoService.updateListState(addCardInfoVo.getComId());
                        } catch (Exception exception) {
                            log.info("消费设备白名单更新失败 exception{{}} ", exception.getMessage());
                            return ResultUtil.error(ResultEnum.Err_808);
                        }
                    } else {
                        log.info("卡已经被此人使用  直接返回成功 【{}】", addCardInfoVo);
                    }
                    return ResultUtil.success();
                } else {
                    log.info("卡已经使用 【{}】", addCardInfoVo);
                    return ResultUtil.error(ResultEnum.Err_812);
                }
            }

            Integer selectCount = xfCardInfoService.selectCardCount(addCardInfoVo.getComId(), addCardInfoVo.getPId());
            if (selectCount > 0) {
                log.info("人员已发卡 ，【{}】", addCardInfoVo);
                return ResultUtil.error(ResultEnum.Err_812);
            }
            Integer integer = xfCardInfoService.selectAccountNo(addCardInfoVo.getComId(), addCardInfoVo.getAccountNo());
            if (integer > 0) {
                log.info("{{}}账号已发卡", addCardInfoVo.getAccountNo());
                return ResultUtil.error(ResultEnum.Err_815);
            }
            EntityCardInfo entityCardInfo = new EntityCardInfo();
            entityCardInfo.setComId(addCardInfoVo.getComId());
            entityCardInfo.setPId(addCardInfoVo.getPId());
            entityCardInfo.setCardNo(addCardInfoVo.getCardNo());

            entityCardInfo.setAccountNo(addCardInfoVo.getComId() + "P" + addCardInfoVo.getPId());
            entityXfAccountInfo = xfAccountInfoService.GetXFAccount(addCardInfoVo.getComId(), addCardInfoVo.getPId().intValue(), 0);
            if (entityXfAccountInfo != null) {
                entityCardInfo.setAccountNo(entityXfAccountInfo.getAccountNo());
            }

            entityCardInfo.setCreateUser(addCardInfoVo.getUser());
            entityCardInfo.setUpdateUser(addCardInfoVo.getUser());
            entityCardInfo.setCardState(1);
            entityCardInfo.setEndDate(DateUtils.parseDate(addCardInfoVo.getEndDate()));
            xfCardInfoService.AddCardInfo(addCardInfoVo.getComId(), entityCardInfo);
        } catch (Exception exception) {
            log.info("个人发卡失败:{{}}", exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009, "个人发卡失败");
        }
        try {
            //新增白名单：用comId和pId去查询白名单表xf_white_info是否为空
            //a：不为空，删除消费白名单表xf_white_info所有com_id、p_id匹配的记录。
            //b：为空执行下一步
            //   用com_id=@comId，p_id=@pId，state=0，create_time=系统当前时间，新增入库
            xfWhiteInfoService.insertWhiteInfo(addCardInfoVo.getComId(), addCardInfoVo.getPId(), 0L);
        } catch (Exception exception) {
            log.info("新增消费白名单失败 exception{{}} ", exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_807);
        }

        try {
            //将单位下的所有机器的白名单状态更新为1，
            // Update xf_device_info set list_state=1 where com_id=@comId
            xfDeviceInfoService.updateListState(addCardInfoVo.getComId());
        } catch (Exception exception) {
            log.info("消费设备白名单更新失败 exception{{}} ", exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_808);
        }
        //4.新增一条发卡流水
        try {
            EntityCardRecord entityCardRecord = new EntityCardRecord();
            entityCardRecord.setComId(addCardInfoVo.getComId());
            entityCardRecord.setAccountNo(addCardInfoVo.getAccountNo());
            entityCardRecord.setPId(addCardInfoVo.getPId());
            entityCardRecord.setAccTypeId(addCardInfoVo.getAccTypeId());
            entityCardRecord.setCardNo(addCardInfoVo.getCardNo());
            entityCardRecord.setOperationType(1L);
            entityCardRecord.setCostFee(addCardInfoVo.getCostFee());
            entityCardRecord.setDeposit(addCardInfoVo.getDeposit());
            entityCardRecord.setCreateUser(addCardInfoVo.getUser());
            entityCardRecord.setDayTime(DateUtils.getDate());

            if (entityXfAccountInfo != null) {
                EntityXfAccountType entityXfAccountType = xfAccountTypeService.getXFAccountType(addCardInfoVo.getComId(), entityXfAccountInfo.getAccTypeId());
                if (entityXfAccountType != null) {
                    entityCardRecord.setCostFee(entityXfAccountType.getCostFee());
                    entityCardRecord.setDeposit(entityXfAccountType.getDeposit());
                }
            }

            cardRecordService.AddCardInfo(addCardInfoVo.getComId(), entityCardRecord);
        } catch (Exception exception) {
            log.info("个人发卡記錄失败:{{}}", exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009, "个人发卡記錄失败");
        }
        return ResultUtil.success();
    }

    /**
     * 个人账户挂失/解挂（updatecardState）
     */
    @PostMapping(PayConfigUrl.Url_UpdatecardState)
    public Result UpdatecardState(@RequestBody UpdatecardStateVo updatecardStateVo) {
        log.info("个人账户挂失/解挂請求參數{{}}", updatecardStateVo);
        try {
            xfCardInfoService.UpdatecardState(updatecardStateVo.getComId(), updatecardStateVo);
        } catch (Exception exception) {
            log.info("个人账户挂失/解挂失败:{{}}", exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009, "个人账户挂失/解挂失败");
        }
        try {
            //新增白名单：用comId和pId去查询白名单表xf_white_info是否为空
            //a：不为空，删除消费白名单表xf_white_info所有com_id、p_id匹配的记录。
            //b：为空执行下一步
            //   用com_id=@comId，p_id=@pId，state=0，create_time=系统当前时间，新增入库
            Long state = 0l;
            //判断人是否删除
            EntityPersonnelInfo entityPersonnelInfo = personnelInfoService.getOnePersonInfo(updatecardStateVo.getComId(), updatecardStateVo.getPId());
            if (entityPersonnelInfo == null) {
                state = 1l;
            }
            xfWhiteInfoService.insertWhiteInfo(updatecardStateVo.getComId(), updatecardStateVo.getPId(), state);
        } catch (Exception exception) {
            log.info("新增消费白名单失败 exception{{}} ", exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_807);
        }

        try {
            //将单位下的所有机器的白名单状态更新为1，
            // Update xf_device_info set list_state=1 where com_id=@comId
            xfDeviceInfoService.updateListState(updatecardStateVo.getComId());
        } catch (Exception exception) {
            log.info("消费设备白名单更新失败 exception{{}} ", exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_808);
        }
        //4.新增一条发卡流水
        try {
            EntityCardRecord entityCardRecord = new EntityCardRecord();
            entityCardRecord.setComId(updatecardStateVo.getComId());
            entityCardRecord.setPId(updatecardStateVo.getPId());
            entityCardRecord.setAccTypeId(updatecardStateVo.getAccTypeId());
            entityCardRecord.setCardNo(updatecardStateVo.getCardNo());
            entityCardRecord.setAccountNo(updatecardStateVo.getAccountNo());
            if (updatecardStateVo.getCardState().equals(0)) {
                entityCardRecord.setOperationType(6L);
            }
            if (updatecardStateVo.getCardState().equals(1)) {
                entityCardRecord.setOperationType(5L);
            }
            if (updatecardStateVo.getCardState().equals(2)) {
                entityCardRecord.setOperationType(3L);
            }
            entityCardRecord.setCreateUser(updatecardStateVo.getUser());
            cardRecordService.AddCardInfo(updatecardStateVo.getComId(), entityCardRecord);
        } catch (Exception exception) {
            log.info("个人发卡記錄失败:{{}}", exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009, "个人发卡記錄失败");
        }
        return ResultUtil.success();
    }


    /*
     * @Description:卡操作记录明细列表
     * @Author: lu
     * @Date: 2022/6/23 11:27
     * @param jsonObject:
     * @return: com.ocom.common.resp.Result
     **/
    @PostMapping(PayConfigUrl.Url_CardOperDetailList)
    public Result cardOperDetailList(@RequestBody JSONObject jsonObject) {
        Map<String, Object> map = new HashMap<>();
        try {
            if (jsonObject.getLong("comId") == null || jsonObject.getInteger("page") == null || jsonObject.getInteger("size") == null) {
                return ResultUtil.error(ResultEnum.Err_203);
            }
            List<GetCardRecordListVo> list = cardRecordService.cardOperDetailList(jsonObject.getLong("comId"), jsonObject);
            PageInfo<GetCardRecordListVo> getListRechargeRVoPageInfo = new PageInfo<>(list);
            map.put("total", getListRechargeRVoPageInfo.getTotal());
            map.put("list", getListRechargeRVoPageInfo.getList());
            return ResultUtil.success(map);
        } catch (Exception e) {
            log.error("获取卡操作记录明细列表{{}}", e);
            return ResultUtil.error(ResultEnum.Err_4005, jsonObject);
        }

    }

    /*
     * @Description:8.2.卡操作汇总（CountCardOperRecord）
     * @Author: lu
     * @Date: 2022/6/24 9:02
     * @param jsonObject:
     * @return: com.ocom.common.resp.Result
     **/
    @PostMapping(PayConfigUrl.Url_CountCardOperRecord)
    public Result countCardOperRecord(@RequestBody JSONObject jsonObject) {
        Map<String, Object> map = new HashMap<>();
        try {
            if (jsonObject.getLong("comId") == null || jsonObject.getInteger("page") == null || jsonObject.getInteger("size") == null) {
                return ResultUtil.error(ResultEnum.Err_203);
            }
            List<EntityCardRecord> list = cardRecordService.countCardOperRecord(jsonObject.getLong("comId"), jsonObject);
            PageInfo<EntityCardRecord> getListRechargeRVoPageInfo = new PageInfo<>(list);
            Long costFeeSums = getListRechargeRVoPageInfo.getList().stream().mapToLong(EntityCardRecord::getCostFeeSum).sum();
            Integer issuingTimeSums = getListRechargeRVoPageInfo.getList().stream().mapToInt(EntityCardRecord::getIssuingTimes).sum();
            Integer lossTimeSums = getListRechargeRVoPageInfo.getList().stream().mapToInt(EntityCardRecord::getLossTimes).sum();
            Integer unwindTimeSums = getListRechargeRVoPageInfo.getList().stream().mapToInt(EntityCardRecord::getUnwindTimes).sum();
            Integer checkoutTImeSums = getListRechargeRVoPageInfo.getList().stream().mapToInt(EntityCardRecord::getCheckoutTImes).sum();
            Map<String, Object> sumMap = new HashMap<>();
            sumMap.put("costFeeSums", costFeeSums);
            sumMap.put("issuingTimeSums", issuingTimeSums);
            sumMap.put("lossTimeSums", lossTimeSums);
            sumMap.put("unwindTimeSums", unwindTimeSums);
            sumMap.put("checkoutTImeSums", checkoutTImeSums);
            map.put("total", getListRechargeRVoPageInfo.getTotal());
            map.put("list", getListRechargeRVoPageInfo.getList());
            map.put("sumList", sumMap);
            return ResultUtil.success(map);
        } catch (Exception e) {
            log.error("获取卡操作记录明细列表{{}}", e);
            return ResultUtil.error(ResultEnum.Err_4005, jsonObject);
        }

    }


    // 查询卡信息（getCardInfoByCardNo）
    @PostMapping(PayConfigUrl.Url_GetCardInfoByCardNo)
    public Result getCardInfoByCardNo(Long comId, String cardNo) {
        EntityCardInfo entityCardInfo = xfCardInfoService.selectCount(comId, cardNo);
        if (entityCardInfo == null) {
            return ResultUtil.error(ResultEnum.Err_3044);
        }
        return ResultUtil.success(entityCardInfo);
    }
}
